package org.lc.stk.config;

import org.lc.stk.model.Department;
import org.lc.stk.model.Role;
import org.lc.stk.model.User;
import org.lc.stk.repository.DepartmentRepository;
import org.lc.stk.repository.RoleRepository;
import org.lc.stk.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class DataInitializer {

    @Bean
    public CommandLineRunner initData(
            UserRepository userRepository, 
            RoleRepository roleRepository,
            DepartmentRepository departmentRepository,
            PasswordEncoder passwordEncoder) {
        return args -> {
            System.out.println("开始初始化用户数据...");
            
            // 清空现有数据
            userRepository.deleteAll();
            roleRepository.deleteAll();
            departmentRepository.deleteAll();
            
            // 创建角色
            Role adminRole = new Role("ADMIN");
            Role userRole = new Role("USER");
            roleRepository.save(adminRole);
            roleRepository.save(userRole);
            System.out.println("创建角色成功");

            // 创建根部门（学校）
            Department rootDepartment = new Department();
            rootDepartment.setName("学校");
            rootDepartment.setCode("SCHOOL");
            rootDepartment.setOrderNumber(1);
            rootDepartment.setType("ROOT");
            departmentRepository.save(rootDepartment);
            System.out.println("创建根部门（学校）成功");
            
            // 创建管理员用户
            User adminUser = new User();
            adminUser.setUsername("admin");
            String adminEncodedPassword = passwordEncoder.encode("admin");
            System.out.println("管理员密码哈希: " + adminEncodedPassword);
            adminUser.setPassword(adminEncodedPassword);
            adminUser.addRole(adminRole);
            adminUser.setDepartment(rootDepartment);
            userRepository.save(adminUser);
            System.out.println("创建管理员用户成功");
            
            // 创建普通用户
            User normalUser = new User();
            normalUser.setUsername("user");
            String userEncodedPassword = passwordEncoder.encode("user");
            System.out.println("普通用户密码哈希: " + userEncodedPassword);
            normalUser.setPassword(userEncodedPassword);
            normalUser.addRole(userRole);
            normalUser.setDepartment(rootDepartment);
            userRepository.save(normalUser);
            System.out.println("创建普通用户成功");
            
            System.out.println("用户数据初始化完成");
        };
    }
}